// pages/product/product.js
var Zan = require('../../dist/index.js');
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
let WxNotificationCenter = require('../../utils/WxNotificationCenter.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();
var start = 0;
var start1 = 0;
let constants = null;
// var eventStatus = 0;
let selecedProduct = null;
let delIndex = 0;
Page(Object.assign({}, Zan.Tab, Zan.TopTips, Zan.Toast, {
  /**
   * 页面的初始数据
   */
  data: {
    tab: {},
    selectedId: 0,
    nearbyStore: [],
    menu: [],
    title: '',
    products: [],
    product: {},
    storeId: null,
    typeId: null,
    count: 0,
    allCount: 1,
    specDialog: false,
    specTitle: '',
    lat: '',
    lng: '',
    currProPrice: 0,
    oldPrice: 0,
    specArr: [],
    specArrCon: [],
    mobile: null,
    productId: '',
    specIdx: '',
    specDetails1: '',
    specDetails2: '',
    specDetails3: '',
    shopCarDialog: false,
    items: [],
    specId: null,
    limitCount: 0,
    storeCount: 0,
    batting: false,
    itemsCount: 0,
    // TenantDistribution: [],
    nodata: {
      msg: '',
      notype: 2,
      imgurl: '../../images/nodatas.png',
      nourl: ''
    },
    nodata_s: {
      msg: '',
      notype: 2,
      imgurl: '../../images/nodatas.png',
      nourl: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();
    constants = new app.Constants();


    wx.showLoading({
      title: '',
    })
    // var that = this;
    // wx.getLocation({
    //   type: 'wgs84',
    //   success: function (res) {
    //     let latitude = res.latitude;
    //     let longitude = res.longitude;
    //     that.setData({
    //       lng: longitude,
    //       lat: latitude
    //     })
    //   }
    // })

    if (app.globalData.userId) {
      bind(options);
    } else {
      // 由于 openId 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoCallback = res => {
        bind(options);
      }
    }

    this.onPullDownRefresh();
    // 注册列表刷新事件
    WxNotificationCenter.addNotification("productRefreshNotification", this.refreshNotification, this);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function(options) {

    var linkId = wx.getStorageSync("linkId");
    if (linkId != '' || linkId == "0") {
      this.setData({
        typeId: linkId,
        selectedId: linkId
      })
    }
    
    this.setData({
      nearbyStore: app.globalData.store,
      storeId: app.globalData.store.id,
      items: []
    })
    getNowFormatDate(this);
    network._post_page_json(this, api.getShoppingCartList, start1, { userId: app.globalData.userId, storeId: app.globalData.store.id}, successCar);

    // if (linkId) {
    this.setData({
      menu: [],
      products: [],
    });
    network._post_json(this, api.getProductGroup, {}, successType);
    // }else{
    //   console.log("selectedIdselectedIdselectedIdselectedId"+this.data.selectedId);
    //   if(this.data.selectedId){
    //     this.setData({
    //       products: [],
    //     });
    //     network._post_json(this, api.getProductList, { typeId: this.data.menu[this.data.selectedId].id, storeId: this.data.storeId }, success);
    //   }

    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    wx.removeStorageSync('linkId');

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    WxNotificationCenter.removeNotification("productRefreshNotification", this);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.stopPullDownRefresh();
    //start1 = 0;
    // this.setData({
    //   menu: [],
    //   products: [],
    //   items: [],
    // })
    // var linkId = wx.getStorageSync("linkId");
    // if (linkId) {

    // }else{
    //   console.log("页面相关事件处理函数--监听用户下拉动作");
    //   network._post_json(this, api.getProductGroup, {}, successType);
    // }


  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    // if (this.data.product.length < this.data.recordsTotal) {
    //   start = start + 20;
    //   network._post_page_json(this, api.getProductList, start, { typeId: this.data.menu[this.data.selectedId].id, storeId: this.data.storeId }, success);

    // }
  },
  refreshNotification: function() {
    this.onPullDownRefresh();
  },
  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  NoProduct: function(e) {
    this.showZanTopTips(this.prompt, "购物车是空的");
  },
  Specclose: function(e) {
    this.setData({
      specDialog: !this.data.specDialog,
    })
  },
  shopCarDialog: function(e) {
    this.setData({
      shopCarDialog: !this.data.shopCarDialog
    })
  },
  /** */
  // goStore: function () {
  //   wx.navigateTo({
  //     url: '/pages/myself/store/StoreInfo' + '?lng=' + this.data.lng + '&lat=' + this.data.lat,
  //   })
  // },
  /**
   * 进入搜索页面
   */
  cancel: function() {
    this.setData({
      title: ''
    })
  },

  /**
   * 点击商品进入商品详情
   */
  onProductItemClick: function(e) {
    var id = e.currentTarget.dataset.id;

    // 店铺
    // let store = {};
    // store.id = this.data.nearbyStore.id;
    // store.name = this.data.nearbyStore.name;
    // store.imgUrl = this.data.nearbyStore.img.imgUrl;
    // store.district = this.data.nearbyStore.district;
    // store.address = this.data.nearbyStore.address;

    wx.navigateTo({
      url: '/pages/product/ProductDetails' + '?productId=' + id + '&store=' + encodeURIComponent(JSON.stringify(this.data.nearbyStore))
    })
  },

  /**
   * 
   */
  handleZanTabChange(e) {
    console.log("+++++++++++++++");
    var componentId = e.componentId;
    var selectedId = e.selectedId;

    this.setData({
      products: [],
      selectedId: selectedId,
      [`${componentId}.selectedId`]: selectedId
    });

    //start = 0;
    network._post_json(this, api.getProductList, {
      typeId: this.data.menu[selectedId].id,
      storeId: this.data.storeId
    }, success);
  },

  selectSpec: function(e) {
    //selecedProduct = e.currentTarget.dataset.item;
    var title = e.currentTarget.dataset.title;
    var productId = e.currentTarget.dataset.id;
    var specIdx = e.currentTarget.dataset.idx;
    // var count = e.currentTarget.dataset.count;
    this.data.specArr = JSON.parse(e.currentTarget.dataset.spec);

    let specArray = [];
    for (var n = 0; n < this.data.specArr.length; n++) {
      let spec = {};
      let specDetailArr = [];
      spec.specType = this.data.specArr[n].specType;
      // spec.count = count;
      for (var i = 0; i < this.data.specArr[n].specDetails.length; i++) {
        let specDetail = {};
        specDetail.name = this.data.specArr[n].specDetails[i];
        specDetail.class = '';
        if (i == 0) {
          specDetail.class = "active";
        }
        specDetailArr.push(specDetail);
      }
      specArray.push(spec);
      spec.specDetails = specDetailArr;
    }
    // if (this.data.products[specIdx].count == 0) {
    //   this.data.products[specIdx].count = 1;
    // }

    this.setData({
      specTitle: title,
      specArrCon: specArray,
      specIdx: specIdx,
      // count:count,
      specDialog: !this.data.specDialog
    })
    this.setData({
      productId: productId,
      specDetails1: specArray[0].specDetails[0].name,
      specDetails2: specArray[1] != undefined ? specArray[1].specDetails[0].name : '',
      specDetails3: specArray[2] != undefined ? specArray[2].specDetails[0].name : '',
    })

    getProductPrice(this);
  },

  /**
   * 单规格，减商品数量
   */
  reduce: function(e) {
    var proitem = e.currentTarget.dataset.item;
    var index = e.currentTarget.dataset.index;

    if (proitem.count > 0) {
      proitem.count--;
      this.data.products[index] = proitem;
      for (var c = 0; c < this.data.items.length; c++) {
        if (this.data.items[c].productId == this.data.products[index].id) {
          this.data.items[c].count = '' + this.data.products[index].count + ''
        }
      }
      this.setData({
        products: this.data.products,
        items: this.data.items
      });
      addShoppingCart(this, this.data.products[index]);
      allPrice(this, this.data.items);
    }
  },

  /**
   * 单规格，加商品数量
   */
  add: function(e) {
    var proitem = e.currentTarget.dataset.item;
    var index = e.currentTarget.dataset.index;
    var counts = parseInt(proitem.count) + 1;

    for (var c = 0; c < this.data.items.length; c++) {
      if (this.data.items[c].productId == this.data.products[index].id) {
        this.data.items[c].count = '' + this.data.products[index].count + ''
      }
    }
    //校验数量
    var checkFlag = isSelectedOk(this, this.data.products[index], counts);
    if (checkFlag == -1) {
      this.showZanTopTips(this.prompt, "库存不足");
      return false;
    } else if (checkFlag == -2) {
      this.showZanTopTips(this.prompt, "购买数量大于限购数量");
      return false;
    } else {
      this.data.products[index].count++;
      this.setData({
        products: this.data.products,
        items: this.data.items
      });
      addShoppingCart(this, this.data.products[index]);
      allPrice(this, this.data.items);
    }
  },

  /**
   * 多规格，减商品数量
   */
  reduceTips: function(e) {
    this.showZanTopTips(this.prompt, '多规格商品只能在购物车删除');
  },
  reduce2: function(e) {
    // let product = this.data.products[this.data.specIdx];
    if (this.data.count > 1) {
      this.data.count--;
      // this.data.products[this.data.specIdx] = product;
      this.setData({
        count: this.data.count,
        // products: this.data.products,
      });
    }
  },

  /**
   * 多规格，加商品数量
   */
  add2: function(e) {
    // let product = this.data.products[this.data.specIdx];
    var counts = parseInt(this.data.count) + 1;

    //校验数量
    var checkFlag = isSelectedOk(this, this.data.products[this.data.specIdx], counts);
    if (checkFlag == -1) {
      this.showZanTopTips(this.prompt, "库存不足");
    } else if (checkFlag == -2) {
      this.showZanTopTips(this.prompt, "购买数量大于限购数量");
    } else {
      if (checkFlag == 1) {
        // product.currentPrice = product.currentPrice * product.count;
        this.data.count++;
        this.setData({
          count: this.data.count,
          products: this.data.products,
        });
        console.log("==========多规格商品数量=========");
        console.log(this.data.count);
      }
    }

  },
  /**
   * 购物车，减商品数量
   */
  reduce3: function(e) {
    var itemCon = e.currentTarget.dataset.item;
    var itemIdx = e.currentTarget.dataset.index;
    if (itemCon.count > 0) {
      itemCon.count--;
      this.data.items[itemIdx] = itemCon;
      for (var c = 0; c < this.data.products.length; c++) {
        if (this.data.items[itemIdx].productId == this.data.products[c].id) {
          this.data.products[c].count = this.data.items[itemIdx].count
        }
      }
      this.setData({
        products: this.data.products,
        items: this.data.items
      });

      addShoppingCart2(this, this.data.items[itemIdx]);
      allPrice(this, this.data.items);
    }
  },

  /**
   * 购物车，加商品数量
   */
  add3: function(e) {
    var itemCon = e.currentTarget.dataset.item;
    var itemIdx = e.currentTarget.dataset.index;
    var counts = parseInt(itemCon.count) + 1;

    //校验数量
    var checkFlag = isSelectedOk2(this, this.data.items[itemIdx], counts);
    if (checkFlag == -1) {
      this.showZanTopTips(this.prompt, "库存不足");
    } else if (checkFlag == -2) {
      this.showZanTopTips(this.prompt, "购买数量大于限购数量");
    } else {
      if (checkFlag == 1) {
        this.data.items[itemIdx].count++;
        for (var c = 0; c < this.data.products.length; c++) {
          if (this.data.items[itemIdx].productId == this.data.products[c].id) {
            this.data.products[c].count = this.data.items[itemIdx].count
          }
        }
        this.setData({
          products: this.data.products,
          items: this.data.items
        });
        addShoppingCart2(this, this.data.items[itemIdx]);
        allPrice(this, this.data.items);
      }
    }

  },
  //选择一个规格后
  specSelect: function(e) {
    var currData = e.currentTarget.dataset;
    var fatidx = currData.fatidx;
    var subidx = currData.subidx;
    var currBind = this.data.specArrCon[fatidx].specDetails[subidx];
    currBind.class = "active";

    //处理当前选择的规格类型的其他规格
    for (var n = 0; n < this.data.specArrCon[fatidx].specDetails.length; n++) {
      if (this.data.specArrCon[fatidx].specDetails[n].class == "active" && subidx != n) {
        this.data.specArrCon[fatidx].specDetails[n].class = "";
      }
    }
    this.setData(this.data);
    //计算所选规格价格
    var selectedSpec = [];
    for (var m = 0; m < this.data.specArrCon.length; m++) {
      for (var n = 0; n < this.data.specArrCon[m].specDetails.length; n++) {
        if (this.data.specArrCon[m].specDetails[n].class == "active") {
          selectedSpec.push(this.data.specArrCon[m].specDetails[n].name);
        }
      }
    }
    //console.log(selectedSpec);
    this.setData({
      specDetails1: selectedSpec[0],
      specDetails2: selectedSpec[1] != undefined ? selectedSpec[1] : '',
      specDetails3: selectedSpec[2] != undefined ? selectedSpec[2] : '',
    })

    getProductPrice(this);
  },
  //购物车列表
  shopCarList: function(e) {
    if (this.data.shopCarDialog) {

    } else {
      start1 = 0;
      this.setData({
        items: [],
      });
      network._post_page_json(this, api.getShoppingCartList, start1, { userId: app.globalData.userId, storeId: app.globalData.store.id}, successCar);
    }
    this.setData({
      shopCarDialog: !this.data.shopCarDialog
    })
  },
  /**
   * 如果用户已授权，并且用户昵称不为空，则直接弹框
   */
  chooseSpan: function(e) {
    // var event = e.currentTarget.dataset.event;
    var index = e.currentTarget.dataset.idx;
    if (this.data.count <= 0) {
      this.showZanTopTips(this.prompt, "请选择数量");
    } else {
      addShoppingCart(this, this.data.products[index]);
    }

  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function(e) {
    //开始触摸时 重置所有删除
    this.data.items.forEach(function(v, i) {
      if (v.isTouchMove) //只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      items: this.data.items
    })
  },
  //滑动事件处理
  touchmove: function(e) {
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    that.data.items.forEach(function(v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      items: that.data.items
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function(start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  /**
   * 删除事件
   */
  // del: function (e) {
  //   delIndex = e.currentTarget.dataset.index;
  //   var shopCart = this.data.items[delIndex];
  //   var that = this
  //   wx.showModal({
  //     title: '提示',
  //     content: '确定删除吗？',
  //     success: function (res) {
  //       if (res.confirm) {
  //         network._post_json(that, api.delShoppingCart, { shoppingCarId: shopCart.id, is_del: 0 }, delSuccess);

  //       } else if (res.cancel) {
  //       }
  //     }
  //   })
  // },
  alldel: function(e) {
    let allProId = [];
    for (var c = 0; c < this.data.items.length; c++) {
      let ProIdItems = this.data.items[c].id;
      allProId.push(ProIdItems);
    }
    allProId = allProId.join(',');
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定清空吗？',
      success: function(res) {
        if (res.confirm) {
          network._post_json(that, api.delShoppingCart, {
            shoppingCarId: allProId,
            is_del: 1
          }, delSuccess);
          that.setData({
            shopCarDialog: !that.data.shopCarDialog
          })
          that.setData({
            menu: [],
            products: [],
            items: [],
          });
          network._post_json(that, api.getProductGroup, {}, successType);
        } else if (res.cancel) {}
      }
    })
  },
  /**
   * 进入下一步提交订单
   */
  pay: function(e) {
    getNowFormatDate(this);
    //校验数量
    for (let c = 0; c < this.data.items.length; c++) {
      var checkFlag = isSelectedOk2(this, this.data.items[c], this.data.items.count);
      if (checkFlag == -1) {
        this.showZanTopTips(this.prompt, "库存不足");
      } else if (checkFlag == -2) {
        this.showZanTopTips(this.prompt, "购买数量大于限购数量");
      }
    }
    
    // 商品
    let products = [];
    let count = 1;
    for (var i = 0; i < this.data.items.length; i++) {
      let product = {};
      let car = this.data.items[i];
      product.carid = car.id;
      product.id = car.productId;
      product.title = car.product.title;
      product.imgUrl = car.product.imgUrl;
      // product.price = car.oldPrice;
      if (car.Productspecgroups) {
        product.price = car.Productspecgroups.currentPrice;
        product.memberPrice = car.Productspecgroups.memberPrice;
      } else {
        product.price = car.product.currentPrice;
        product.memberPrice = car.product.memberPrice;
      }
      
      product.weight = car.product.weight;
      product.count = car.count;
      if (car.product.isService == 1) {
        product.isService = "1";
      }
      if (car.Productspecgroups) {
        let name = "";
        if (car.Productspecgroups.specDetails1) {
          name += car.Productspecgroups.specDetails1;
        }
        if (car.Productspecgroups.specDetails2) {
          name += '+' + car.Productspecgroups.specDetails2;
        }
        if (car.Productspecgroups.specDetails3) {
          name += '+' + car.Productspecgroups.specDetails3;
        }
        product.specId = car.Productspecgroups.id;
        product.specName = name;
        product.weight = car.Productspecgroups.weight;
      }
      products.push(product);
      count += parseInt(car.count);
    }

    // // 配送费
    // let packingCharge = 0;
    // let freight = 0;
    // if (this.data.TenantDistribution.logistics) {
    //   packingCharge = this.data.TenantDistribution.logistics.packingCharge * count;
    //   freight = this.data.TenantDistribution.logistics.freight;
    // } else if (this.data.TenantDistribution.pickedUp) {
    //   packingCharge = this.data.TenantDistribution.pickedUp.packingCharge * count;
    // }

    // 店铺
    let store = {};
    store.id = this.data.nearbyStore.id;
    store.name = this.data.nearbyStore.name;
    store.imgUrl = this.data.nearbyStore.img.imgUrl;
    // store.province = this.data.nearbyStore.province;
    // store.city = this.data.nearbyStore.city;
    store.district = this.data.nearbyStore.district;
    store.address = this.data.nearbyStore.address;

    wx.navigateTo({
      url: '/pages/pay/Pay?shoppingCar=' + encodeURIComponent(JSON.stringify(products)) + '&store=' + encodeURIComponent(JSON.stringify(store))
    })
    
  }
}))

var bind = function(options) {
  if (options.shared) {
    wx.request({
      url: api.bindUserFormQRcode,
      data: {
        openId: app.globalData.openId,
        userId: app.globalData.userId,
        tenantId: app.globalData.tenantId,
        distributorId: options.shared,
        productId: options.productId
      },
      method: 'POST',
      success: function(res) {}
    });
  }
}
var getNowFormatDate = function(that) {
  var date = new Date();
  var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
  var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
  var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  var currentdate = h + ":" + m + ":" + s;
  if (that.data.nearbyStore.openTime > currentdate || that.data.nearbyStore.closeTime < currentdate) {
    that.setData({
      batting: true
    })
  } else {
    that.setData({
      batting: false
    })
  }
}
//门店
// var successStore = function (that, res) {
//   if (res.data.data) {
//     that.setData({
//       nearbyStore: res.data.data,
//       storeId: res.data.data.id
//     })
//     // network._post_json(that, api.getTenantDistribution, { tenantId: app.globalData.tenantId, storeId: res.data.data.id }, successDistribution);

//   }
// }
// 获取商品分类结果
var successType = function(that, res) {
  if (res.data.data) {
    that.setData({
      menu: that.data.menu.concat(res.data.data)
    })

    var menuItems = []
    for (var i = 0; i < that.data.menu.length; i++) {
      var menuItem = {};
      menuItem.id = i;
      menuItem.title = that.data.menu[i].name;
      menuItems.push(menuItem);
    }

    var index = that.data.selectedId;
    console.log("typeId=====================" + that.data.typeId);
    console.log("selectedId=====================" + that.data.selectedId);
    // if (that.data.typeId) {
      for (var i = 0; i < that.data.menu.length; i++) {
        if (that.data.menu[i].id == that.data.typeId) {
          index = i;
        }
      }
    // } else {
    //   index = 0;
    // }

    that.setData({
      tab: {
        list: menuItems,
        scroll: false,
        selectedId: index
      }
    })
    // start = 0;
    if (that.data.typeId) {
      network._post_json(that, api.getProductList, {
        typeId: that.data.typeId,
        storeId: that.data.storeId
      }, success);
    } else {
      network._post_json(that, api.getProductList, {
        typeId: that.data.menu[that.data.selectedId].id,
        storeId: that.data.storeId
      }, success);
    }


  }
}

// 获取商品列表结果
var success = function(that, res) {
  if (res.data.data) {
    var proArr = that.data.products.concat(res.data.data);
    let proCountArr = [];

    for (var a = 0; a < proArr.length; a++) {
      proArr[a].count = 0;
      for (var c = 0; c < that.data.items.length; c++) {
        if (that.data.items[c].productId == proArr[a].id) {
          proArr[a].count = that.data.items[c].count
        }
      }
    }
    that.setData({
      products: proArr
    })
  }
}

//获取多规格商品分类价格
var getProductPrice = function(that) {
  //价格
  network._post_json(that, api.getProductPrice, {
    productId: that.data.productId,
    specDetails1: that.data.specDetails1,
    specDetails2: that.data.specDetails2,
    specDetails3: that.data.specDetails3
  }, successPrice);
}

/**
 * 计算购物车商品的总价
 */
var allPrice = function(that, items) {

  let oldPrice = 0;

  if (items.length != 0) {
    for (var i = 0; i < items.length; i++) {
      if (items[i].Productspecgroups) {
        oldPrice += items[i].Productspecgroups.currentPrice * items[i].count;
      } else {
        oldPrice += items[i].product.currentPrice * items[i].count;
      }
    }
    // if (that.data.TenantDistribution.logistics) {
    //   oldPrice = oldPrice + parseInt(that.data.TenantDistribution.logistics.packingCharge) + parseInt(that.data.TenantDistribution.logistics.freight)
    // } else if (that.data.TenantDistribution.pickedUp) {
    //   oldPrice = oldPrice + parseInt(that.data.TenantDistribution.pickedUp.packingCharge)
    // }

    that.setData({
      oldPrice: oldPrice,
    })

    // if (that.data.count == 0) {
    //   that.setData({
    //     oldPrice: 0
    //   })
    // }
  } else {
    that.setData({
      oldPrice: 0
    })
  }

}

//校验当前选择的规格及数量是否可以购买
var isSelectedOk = function(that, product, counts) {
  // console.log(counts);
  // console.log(product.limitCount);

  //多规格
  if (product.specClass == 2) {
    if (that.data.isStore == 0) {
      if (that.data.limitCount != 0){
        if (counts > that.data.limitCount) {
          //数量超出限购数量
          return -2;
        }
        return 1;
      }
      return 1;
    } else {
      if (that.data.limitCount != 0) {
        if (that.data.storeCount <= 0 || that.data.storeCount < counts) {
          //库存不足
          return -1;
        } else if (counts > that.data.limitCount) {
          //数量超出限购数量
          return -2;
        } else {
          return 1;
        }
      }else{
        if (that.data.storeCount <= 0 || that.data.storeCount < counts) {
          //库存不足
          return -1;
        }else {
          return 1;
        }
      }
    }
  } else {
    if (product.isStore == 0) {
      if (product.limitCount != 0) {
        if (counts > product.limitCount) {
          //数量超出限购数量
          return -2;
        }
        return 1;
      }
      return 1;
    } else {
      if (product.limitCount != 0) {
        if (product.storeCount <= 0 || product.storeCount < counts) {
          //库存不足
          return -1;
        } else if (counts > product.limitCount) {
          //数量超出限购数量
          return -2;
        } else {
          return 1;
        }
      }else{
        if (product.storeCount <= 0 || product.storeCount < counts) {
          //库存不足
          return -1;
        } else {
          return 1;
        }
      }
      
    }

  }
}
//校验购物车当前选择的规格及数量是否可以购买
var isSelectedOk2 = function(that, product, counts) {
  //多规格
  
  if (product.product.specClass == 2) {
    if (product.Productspecgroups.isStore == 0) {
      if (product.Productspecgroups.limitCount != 0) {
        if (counts > product.Productspecgroups.limitCount) {
          //数量超出限购数量
          return -2;
        }
        return 1;
      }
      return 1;
    } else {
      if (product.Productspecgroups.limitCount != 0) {
        if (product.Productspecgroups.storeCount <= 0 || product.Productspecgroups.storeCount < counts) {
          //库存不足
          return -1;
        } else if (counts > product.Productspecgroups.limitCount) {
          //数量超出限购数量
          return -2;
        } else {
          return 1;
        }
      }else{
        if (product.Productspecgroups.storeCount <= 0 || product.Productspecgroups.storeCount < counts) {
          //库存不足
          return -1;
        }else {
          return 1;
        }
      }
      
    }

  } else {
    if (product.product.isStore == 0) {
      if (product.product.limitCount != 0) {
        if (counts > product.product.limitCount) {
          //数量超出限购数量
          return -2;
        }
        return 1;
      }
      return 1;
    } else {
      if (product.product.limitCount != 0) {
        if (product.product.storeCount <= 0 || product.product.storeCount < counts) {
          //库存不足
          return -1;
        } else if (counts > product.product.limitCount) {
          //数量超出限购数量
          return -2;
        } else {
          return 1;
        }
      } else {
        if (product.product.storeCount <= 0 || product.product.storeCount < counts) {
          //库存不足
          return -1;
        }else {
          return 1;
        }
      }
      
    }

  }
}

var successCar = function(that, res) {
  that.setData({
    itemsCount: 0
  })
  if (res.data.data) {
    for (var c = 0; c < res.data.data.list.length; c++) {
      that.data.itemsCount += parseInt(res.data.data.list[c].count);
      if (res.data.data.list[c].product.specClass == 2){
        if (!res.data.data.list[c].Productspecgroups){
          network._post_json(that, api.delShoppingCart, { shoppingCarId: res.data.data.list[c].id, is_del: 0 }, delSuccess);
        }
      }else{
        // if (!res.data.data.list[c].Productspecgroups) {
        //   network._post_json(that, api.delShoppingCart, { shoppingCarId: res.data.data.list[c].id, is_del: 0 }, delSuccess);
        // }
      }
    }

    that.setData({
      items: res.data.data.list,
      itemsCount: that.data.itemsCount
    })
    // for (var d = 0; d < that.data.products.length; d++) {
    //   for (var c = 0; c < that.data.items.length; c++) {
    //     if (that.data.items[c].productId == that.data.products[d].id) {
    //       that.data.products[d].count = that.data.items[c].count
    //     }
    //   }
    // }
    allPrice(that, res.data.data.list)
  }
}
// var successDistribution = function (that, res) {
//   if (res.data.data) {
//     that.setData({
//       TenantDistribution: res.data.data
//     })

//     console.log(that.data.TenantDistribution);

//   }
// }
var addSuccess = function(that, res) {

  network._post_page_json(that, api.getShoppingCartList, start1, { userId: app.globalData.userId, storeId: app.globalData.store.id}, successCar);
  // allPrice(that, that.data.items);
  that.showZanToast('添加成功');
}
//商品列表添加修改购物车
var addShoppingCart = function(that, products) {
  console.log(products);
  // if (that.data.product.isVirtual == 0 && that.data.product.isActive == 1) {
  //多规格
  if (products.specClass == 2) {
    network._post_json(that, api.addShoppingCart, {
      productId: products.id,
      specId: that.data.specId,
      count: that.data.count,
      storeId: that.data.storeId,
      userId: app.globalData.userId
    }, addSuccess);
    that.setData({
      specDialog: !that.data.specDialog
    })
  } else {
    // 没有规格的商品
    network._post_json(that, api.addShoppingCart, {
      productId: products.id,
      count: products.count,
      storeId: that.data.storeId,
      userId: app.globalData.userId
    }, addSuccess);
  }

  // } else {
  //   that.showZanTopTips(that.prompt, '商品已下架');
  // }
}
//购物车列表添加修改
var addShoppingCart2 = function(that, items) {
  // console.log(items);
  //多规格
  if (items.product.specClass == 2) {
    network._post_json(that, api.addShoppingCart, {
      productId: items.product.id,
      specId: items.specId,
      count: items.count,
      storeId: that.data.storeId,
      userId: app.globalData.userId
    }, addSuccess);
  } else {
    // 没有规格的商品
    network._post_json(that, api.addShoppingCart, {
      productId: items.product.id,
      count: items.count,
      storeId: that.data.storeId,
      userId: app.globalData.userId
    }, addSuccess);
  }

  // } else {
  //   that.showZanTopTips(that.prompt, '商品已下架');
  // }
}

var successPrice = function(that, res) {
  that.setData({
    count: 0
  })

  if (res.data.data) {
    for (var c = 0; c < that.data.items.length; c++) {
      if (that.data.items[c].specId == res.data.data.specId) {
        that.data.count = that.data.items[c].count;
        that.setData({
          count: that.data.count
        })
      }
    }

    that.setData({
      currProPrice: res.data.data.currentPrice ? res.data.data.currentPrice : 0,
      specId: res.data.data.specId,
      limitCount: res.data.data.limitCount,
      storeCount: res.data.data.storeCount,
      isStore: res.data.data.isStore,
    })

  }
}
var delSuccess = function(that, res) {
  if (res.data.data) {
    network._post_page_json(that, api.getShoppingCartList, start1, { userId: app.globalData.userId, storeId: app.globalData.store.id}, successCar);
    that.onPullDownRefresh();
  }
}